# ~*~ coding: utf-8 ~*~
import sys
import os
import yaml

from flask import current_app
from apps.common.utils import gen_datetime_path
from apps.ops.celery.utils import create_or_update_celery_periodic_task, delete_celery_periodic_task

__all__ = ['create_or_update_periodic_task', 'delete_periodic_task']


def create_or_update_periodic_task(periodic, interval=None, crontab=None):
    task = {
        periodic.id: {
            'task': 'apps.tasks.tasks.run_periodic_task',
            'interval': interval.schedule if interval else None,
            'crontab': crontab.schedule if crontab else None,
            'args': [periodic.id],
            'kwargs': {},
            'enabled': periodic.enabled
        }
    }
    create_or_update_celery_periodic_task(task)


def delete_periodic_task(periodic):
    delete_celery_periodic_task(periodic.id)


class TeeObj:
    origin_stdout = sys.stdout

    def __init__(self, file_obj):
        self.file_obj = file_obj

    def write(self, msg):
        self.origin_stdout.write(msg)
        self.file_obj.write(msg.encode('utf-8'))
        self.flush()

    def flush(self):
        self.origin_stdout.flush()
        self.file_obj.flush()

    def close(self):
        self.file_obj.close()

    def fileno(self):
        return self.file_obj.fileno()


def gen_log_absolute_path(log_name):
    log_path = os.path.join(current_app.config.get('TASKS_LOG_DIR'), gen_datetime_path())
    if not os.path.exists(log_path):
        os.makedirs(log_path, exist_ok=True)
    return os.path.join(log_path, log_name)


def gen_log_relative_path(log_name):
    return os.path.join(gen_datetime_path(), log_name)


def yaml_host_replace(content, hosts):
    res = yaml.safe_load(content)
    for r in res:
        r['hosts'] = hosts
    content = yaml.safe_dump(res)
    return content

